/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package com.edu.kamai.persistence.dao;

import com.edu.kamai.persistence.beans.User;
import java.util.List;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.hibernate.Session;
import org.hibernate.Transaction;

/**
 *
 * @author Administrator
 */
public class UserDAO {
    private static final Log log = LogFactory.getLog(User.class);
    public static final String USER_BEAN = "com.edu.kamai.persistence.beans.User";
    private Session session = null;
    
    public UserDAO(){
        this.session  = kamaiHibernateUtil.getSessionFactory().openSession();
    }
    
    public void addUsr(User user){
        log.debug("save user instance");
        try{
            Transaction tx = session.beginTransaction();
            session.save(user);
            tx.commit();
            log.debug("save successful");
            
        }catch(RuntimeException re){
            log.error("save failed", re);
            throw re;
        }
    }
    
    public void updateUsr(User user){
        log.debug("update user instance");
        try{
            Transaction tx = session.beginTransaction();
            session.update(user);
            tx.commit();
            log.debug("update successful");
            
        }catch(RuntimeException re){
            log.error("update failed",re);
            throw re;
        }
    }
    
    public User findUser(String uid){
        log.debug("getting User instance with uid: " + uid);
        try{
            User user = (User)session.get(USER_BEAN, uid);
            return user;
        }catch(RuntimeException re) {
            log.error("get failed", re);
            throw re;
        }
    }
    
    public User chkUsrValid(String usrID,String usrPwd,int role){
        log.debug("check user login " + usrID + ":" + usrID);
        try{
            Transaction tx = session.beginTransaction();
            String hqlStr=new String("from User where user_id='" + usrID +
                        "' and password='" + usrPwd + "' and role=" +  role + " and status=1");
            //System.out.println(hqlStr);
            List<User> list = session.createQuery(hqlStr).list();
            tx.commit();
            return list.size() == 0 ? null : list.get(0);
            
        }catch(Exception e){
            log.error("check login failed", e);
            return null;
        }
    }
    
    public List<User> chekPendingList(){
        log.debug("check the pending user!");
        try{
            Transaction tx = session.beginTransaction();
            String hqlStr=new String("from User where status=0");
            List<User> pending = session.createQuery(hqlStr).list();
            tx.commit();
            return pending;
        }catch(Exception e){
            log.error("check the pending list error",e);
            return null;
        }
    }
}
